import { useEffect, useState } from "react";
import { Button, Card, Form, Input, Space } from "antd";
import type { ColumnsType } from "antd/es/table";
import stockService, { type PageListReq } from "@/api/services/wms/stockService";
import type { WmsStock } from "./entity";
import { toast } from "sonner";
import { t } from "@/locales/i18n";
import CustomTable from "@/components/grid/CustomTable";

export default function WmsStockPage() {
	const [loading, setLoading] = useState(false);
	const [queryParams, setQueryParams] = useState<PageListReq>({
		materialId: undefined,
		batchCode: undefined,
		warehouseId: undefined,
		locationId: undefined,
		areaId: undefined,
		page: 1,
		pageSize: 10,
	});
	const [total, setTotal] = useState(0);
	const [list, setList] = useState<WmsStock[]>([]);

	//动态设置表格高度
	const [tableScrollY, setTableScrollY] = useState(0);
	const PAGE_OFFSET_HEIGHT = 405;
	const updateTableHeight = () => {
		const newHeight = window.innerHeight - PAGE_OFFSET_HEIGHT;
		setTableScrollY(newHeight > 200 ? newHeight : 200); // 保证最小高度
	};

	useEffect(() => {
		updateTableHeight(); // 初始化
		window.addEventListener("resize", updateTableHeight);
		return () => window.removeEventListener("resize", updateTableHeight);
	}, []);

	const columns: ColumnsType<WmsStock> = [
		{
			title: "物料编码",
			width: 120,
			key: "materialCode",
			dataIndex: "materialCode",
		},
		{
			title: "物料名称",
			width: 120,
			key: "materialName",
			dataIndex: "materialName",
		},
		{
			title: "入库批次号",
			width: 120,
			key: "batchCode",
			dataIndex: "batchCode",
		},
		{
			title: "仓库",
			width: 120,
			key: "warehouseName",
			dataIndex: "warehouseName",
		},
		{
			title: "库区",
			width: 120,
			key: "locationName",
			dataIndex: "locationName",
		},
		{
			title: "库位",
			width: 120,
			key: "areaId",
			dataIndex: "areaName",
		},
		{
			title: "供应商",
			width: 120,
			key: "supplierName",
			dataIndex: "supplierName",
		},
		{
			title: "在库数量",
			width: 120,
			key: "qty",
			dataIndex: "qty",
		},
		{
			title: "冻结数量",
			width: 120,
			key: "freezeQty",
			dataIndex: "freezeQty",
		},
		{
			title: "入库时间",
			width: 120,
			key: "inTime",
			dataIndex: "inTime",
		},
		{
			title: "上一次入库时间",
			width: 120,
			key: "lastInTime",
			dataIndex: "lastInTime",
		},
		{
			title: "库存有效期",
			width: 120,
			key: "expireDate",
			dataIndex: "expireDate",
		},
		{
			title: "备注",
			width: 120,
			key: "remark",
			dataIndex: "remark",
		},
		{
			title: "操作",
			fixed: "right",
			key: "operation",
			align: "center",
			width: 100,
			render: (_, record) => (
				<Space>
					<Button
						type="link"
						onClick={() => {
							console.log("View", record);
						}}
					>
						{t("common.view")}
					</Button>
				</Space>
			),
		},
	];

	//加载表格数据
	const fetchPageList = () => {
		setLoading(true);
		stockService
			.pageList(queryParams)
			.then((res) => {
				setList(res.records);
				setTotal(res.total);
			})
			.catch((error) => {
				console.log(error);
				toast.error("获取数据失败！", error);
			})
			.finally(() => {
				setLoading(false);
			});
	};

	// biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
	useEffect(() => {
		fetchPageList();
	}, [queryParams]);

	//选择其他页
	const handlePageChange = (newPage: number, newPageSize: number) => {
		setQueryParams((prev) => ({
			...prev,
			page: newPage,
			pageSize: newPageSize,
		}));
	};

	return (
		<>
			<Card className="mb-4">
				<Form
					layout="inline"
					onFinish={(values) => {
						setQueryParams((prev) => ({
							...prev,
							...values,
							page: 1,
						}));
					}}
				>
					<Form.Item name="materialId" label="产品物料">
						<Input placeholder="请输入产品物料" allowClear />
					</Form.Item>
					<Form.Item name="batchCode" label="入库批次号">
						<Input placeholder="请输入入库批次号" allowClear />
					</Form.Item>
					<Form.Item name="warehouseId" label="仓库">
						<Input placeholder="请输入仓库" allowClear />
					</Form.Item>
					<Form.Item name="locationId" label="库区">
						<Input placeholder="请输入库区" allowClear />
					</Form.Item>
					<Form.Item name="areaId" label="库位">
						<Input placeholder="请输入库位" allowClear />
					</Form.Item>
					<Form.Item>
						<Button type="primary" htmlType="submit">
							查询
						</Button>
						<Button
							className="ml-2"
							onClick={() => {
								setQueryParams({ page: 1, pageSize: 10 });
							}}
						>
							重置
						</Button>
					</Form.Item>
				</Form>
			</Card>
			<div className="h-4" />
			<Card>
				<CustomTable
					loading={loading}
					columnsConfig={columns}
					dataSource={list}
					total={total}
					current={queryParams.page}
					pageSize={queryParams.pageSize}
					onRefresh={fetchPageList}
					onPageChange={handlePageChange}
					selectable
					scroll={{ y: tableScrollY }}
				/>
			</Card>
		</>
	);
}
